﻿package com.urbansquall.preloader
{
	import flash.display.*;
	import flash.events.*;
	import flash.utils.*;
	import flash.text.*;
	
	public class Preloader extends MovieClip
	{
		// It's possible this function will never be called if the load is instant
		protected function beginLoading() : void {}
		// It's possible this function will never be called if the load is instant
		protected function updateLoading( a_percent : Number ) : void {}
		// It's possible this function will never be called if the load is instant, if beginLoading was called, endLoading will be
		protected function endLoading() : void {}
		// This is the qualified class name for the class to instantiate when preloading is complete
		protected function get mainClassName() : String { return "Main"; }
		
		private var m_firstFrame : Boolean = true;
		
		public function Preloader()
		{
			addEventListener( Event.ENTER_FRAME, checkFrame );
		}
		
		private function checkFrame(e:Event):void
		{
			if( currentFrame == totalFrames )
			{
				removeEventListener( Event.ENTER_FRAME, checkFrame );
				startup();
				return;
			}
		
			if( m_firstFrame )
			{
				beginLoading();
				m_firstFrame = false;
				return;
			}
			
			var percent : Number = root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal;
			updateLoading( percent );
		}
		
		private function startup():void
		{
			stop();
			
			if( !m_firstFrame )
			{
				endLoading();
			}
			
			var MainClass:Class = getDefinitionByName( mainClassName ) as Class;
			if( MainClass == null )
			{
				throw new Error( "Preloader:startup. There was no class matching [" + mainClassName + "]. You may need to override Preloader::mainClassName" );
			}
			
			var main : DisplayObject = new MainClass() as DisplayObject;
			if( main == null )
			{
				throw new Error( "Preloader::startup. [" + mainClassName + "] needs to inherit from Sprite or MovieClip." );
			}
			
			addChildAt( main, 0 );
		}
		
	}
	
}